import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { UploadChangeParam } from 'ng-zorro-antd/upload';
import { ApiService } from '@core/api.service';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-operamodal',
    templateUrl: './operaModal.component.html',
    styleUrls: ['./cableRoute.component.less']
})
export class OperaModalComponent implements OnInit {
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() width: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    thisData: any = { 'count': 0, 'id': [] };

    chejianList = [];
    gongquList = [];
    gongquIf = true;
    chezhanList = [];
    chezhanIf = true;
    xbList = [];

    uploadUrl = environment.devscore + '/sysTCable/uploadFile';
    fileList: any = [];
    compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.id === o2.id : o1 === o2);

    constructor(
        private msg: NzMessageService,
        public ls: LocalStorage,
        private apiService: ApiService,
        public datePipe: DatePipe,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        if (!this.width) {
            this.width = '500';
        }
        switch (this.operaType) {
            case 'add':
                this.getApi(() => {
                    this.getAllChejian();
                });
                break;
            case 'edit':
                let editStatus = false;
                let editCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        this.objData = item;
                        editCount += 1;
                        this.thisData.id.push(item.id);
                        editStatus = true;
                    }
                }
                if (editStatus && editCount === 1) {
                    this.getApi(() => {
                        for (const item of this.xbList) {
                            if (item.name === this.objData.lineType) {
                                this.operaData.line = item;
                            }
                        }
                        this.operaData.breaks = this.objData.breaks;
                        this.operaData.drawingName = this.objData.drawingName;
                        this.operaData.wsOrgId = this.objData.wsOrgId;
                        this.apiService.getgongquByCjId(this.objData.wsOrgId).subscribe((res: any) => {
                            this.gongquList = res;
                            this.operaData.waOrgId = this.objData.waOrgId;
                            this.apiService.getStationByOrgId(this.objData.wsOrgId, '1').subscribe((data: any) => {
                                this.chezhanList = data;
                                this.operaData.stationId = this.objData.stationId;
                            });
                        });
                        if (this.objData.drawingUrl) {
                            this.fileList = [{
                                name: this.operaData.drawingName,
                                url: this.objData.drawingUrl
                            }];
                        }
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择数据进行操作');
                }
                break;
            case 'del':
                let delStatus = false;
                for (const item of this.responseData) {
                    if (item.checked) {
                        this.objData = item;
                        this.thisData.count += 1;
                        this.thisData.id.push(item.id);
                        delStatus = true;
                    }
                }
                if (delStatus) {
                    this.getApi(() => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择数据删除');
                }
                break;
        }
    }
    getApi(callback) {
        setTimeout(() => {
            this.Visible = true;
            const allApi = [
                this.http.get(environment.project + '/getAllLine'),
                this.http.get(environment.apiBase + '/csmis/getAllChejian.jwt?yesorno=1')
            ];
            forkJoin(allApi).subscribe((results: any) => {
                if (!results[0].code) {
                    this.xbList = results[0].data;
                }
                if (results[1].length) {
                    for (const item of results[1]) {
                        this.chejianList.push({
                            opValue: !item.opValue ? '0' : item.opValue,
                            opName: item.opName
                        });
                    }
                }
                callback();
            });
        }, 200);
    }
    handleChange(info: UploadChangeParam) {
        switch (info.file.status) {
            case 'done':
                const response = info.file.response;
                if (response) {
                    if (!response.code) {
                        this.fileList.push({
                            name: this.operaData.drawingName,
                            url: response.data[0]
                        });
                    } else {
                        this.msg.error(response.msg);
                    }
                }
                break;
            case 'removed':
                this.fileList = [];
                break;
            case 'error':
                this.msg.error(`${info.file.name} 上传失败`);
                break;
        }
    }
    // 车间
    getAllChejian() {
        this.chejianList = [];
        this.operaData.wsOrgId = '';

        this.apiService.getAllChejian('1').subscribe((res: any) => {
            if (res.length) {
                for (const item of res) {
                    this.chejianList.push({
                        opValue: !item.opValue ? '0' : item.opValue,
                        opName: item.opName
                    });
                }
                this.operaData.wsOrgId = this.chejianList[0].opValue;
                this.getgongquByCjId(this.operaData.waOrgId);
            }
        });
    }
    // 工区
    getgongquByCjId(orgId) {
        if (!orgId) {
            return;
        }
        this.gongquIf = false;
        this.gongquList = [];
        this.operaData.waOrgId = '';

        this.apiService.getgongquByCjId(orgId).subscribe((res: any) => {
            this.gongquIf = true;
            if (res.length) {
                for (const item of res) {
                    this.gongquList.push({
                        opValue: !item.opValue ? '0' : item.opValue,
                        opName: item.opName
                    });
                }
                this.operaData.waOrgId = this.gongquList[0].opValue;
                this.getStationByOrgId(this.operaData.wsOrgId);
            }
        });
    }
    // 车站
    getStationByOrgId(orgId) {
        if (!orgId) {
            return;
        }
        this.chezhanIf = false;
        this.chezhanList = [];
        this.operaData.stationId = '';

        this.apiService.getStationByOrgId(orgId, '1').subscribe((res: any) => {
            this.chezhanIf = true;
            if (res.length) {
                for (const item of res) {
                    this.chezhanList.push({
                        opValue: !item.opValue ? '0' : item.opValue,
                        opName: item.opName
                    });
                }
                this.operaData.stationId = this.chezhanList[0].opValue;
            }
        });
    }
    chejianChange(e) {
        this.getgongquByCjId(e);
    }
    gongquChange(e) {
        this.getStationByOrgId(e);
    }
    Ok() {
        let param: any = this.operaData;
        switch (this.operaType) {
            case 'add':
            case 'edit':
                if (!this.operaData.line || !this.operaData.waOrgId || !this.operaData.wsOrgId ||
                    !this.operaData.stationId || !this.operaData.drawingName) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                    return;
                }
                param.lineType = this.operaData.line.name;
                if (this.fileList.length) {
                    param.drawingUrl = this.fileList[0].url;
                    param.uploadDate = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
                    param.uploadOrg = JSON.parse(this.ls.get('loginInfo')).VC_ORG$ID;
                }
                if (this.operaType === 'edit') {
                    param.id = this.thisData.id.toString();
                }
                delete param.line;
                break;
            case 'del':
                param = this.thisData.id;
                break;
        }
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                }, 200);
            } else {
                if (res.msg) {
                    this.msg.error(res.msg);
                } else {
                    this.msg.error('操作失败');
                }
            }
        });
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}
